const { Client, LocalAuth, MessageMedia } = require('whatsapp-web.js');
const fs = require('fs');
const path = require('path');
const config = require('../config');
const messageService = require('./messageService');
const logger = require('../utils/logger');
const debugLogger = require('../utils/debugLogger');

// 用户WhatsApp客户端映射表
const whatsappClients = new Map();
// 全局QR码映射表
const qrCodes = new Map();
// 连接状态映射表
const connectionStatuses = new Map();

// 联系人状态订阅
const contactSubscriptions = new Map();

// 存储定时器ID，用于清理
const userTimers = new Map();

// 回调函数集合
const callbacks = {
  qrCodeUpdate: new Map(),
  clientReady: new Map(),
  authFailure: new Map(),
  disconnected: new Map(),
  message: new Map(),
  messageStatus: new Map(),
  contactStatus: new Map(),
  batteryStatus: new Map(),
  connectionState: new Map()
};

// 会话管理优化
const sessionManagement = {
  // 会话清理定时器
  cleanupTimers: new Map(),
  
  // 会话恢复尝试计数
  recoveryAttempts: new Map(),
  
  // 最大恢复尝试次数
  maxRecoveryAttempts: 3,
  
  // 会话超时时间（毫秒）
  sessionTimeout: 30 * 60 * 1000, // 30分钟
  
  // 自动清理断开的会话
  scheduleCleanup: (userId) => {
    // 清除现有的清理定时器
    if (sessionManagement.cleanupTimers.has(userId)) {
      clearTimeout(sessionManagement.cleanupTimers.get(userId));
    }
    
    // 设置新的清理定时器
    const timer = setTimeout(async () => {
      try {
        logger.info(`开始清理用户 ${userId} 的断开会话`);
        
        // 清理客户端资源
        cleanupUserResources(userId);
        
        // 更新数据库中的会话状态
        await updateSessionStatus(userId, 'disconnected');
        
        // 清理会话文件
        await cleanupSessionFiles(userId);
        
        logger.info(`用户 ${userId} 的会话清理完成`);
      } catch (error) {
        logger.error(`清理用户 ${userId} 会话时出错:`, error);
      }
    }, sessionManagement.sessionTimeout);
    
    sessionManagement.cleanupTimers.set(userId, timer);
    logger.debug(`为用户 ${userId} 设置会话清理定时器`);
  },
  
  // 取消会话清理
  cancelCleanup: (userId) => {
    if (sessionManagement.cleanupTimers.has(userId)) {
      clearTimeout(sessionManagement.cleanupTimers.get(userId));
      sessionManagement.cleanupTimers.delete(userId);
      logger.debug(`取消用户 ${userId} 的会话清理定时器`);
    }
  },
  
  // 会话恢复机制
  attemptRecovery: async (userId) => {
    const attempts = sessionManagement.recoveryAttempts.get(userId) || 0;
    
    if (attempts >= sessionManagement.maxRecoveryAttempts) {
      logger.warn(`用户 ${userId} 已达到最大恢复尝试次数，停止恢复`);
      return false;
    }
    
    sessionManagement.recoveryAttempts.set(userId, attempts + 1);
    
    try {
      logger.info(`尝试恢复用户 ${userId} 的会话 (第 ${attempts + 1} 次)`);
      
      // 等待一段时间再尝试恢复
      const delay = Math.min(5000 * Math.pow(2, attempts), 30000); // 指数退避，最大30秒
      await new Promise(resolve => setTimeout(resolve, delay));
      
      // 尝试重新初始化
      const result = await initializeWhatsApp(userId);
      
      if (result) {
        logger.info(`用户 ${userId} 会话恢复成功`);
        sessionManagement.recoveryAttempts.delete(userId);
        return true;
      } else {
        logger.warn(`用户 ${userId} 会话恢复失败，将在稍后重试`);
        
        // 如果还有重试机会，安排下次重试
        if (attempts + 1 < sessionManagement.maxRecoveryAttempts) {
          setTimeout(() => {
            sessionManagement.attemptRecovery(userId);
          }, delay * 2);
        }
        
        return false;
      }
    } catch (error) {
      logger.error(`用户 ${userId} 会话恢复过程中出错:`, error);
      return false;
    }
  },
  
  // 重置恢复尝试计数
  resetRecoveryAttempts: (userId) => {
    sessionManagement.recoveryAttempts.delete(userId);
    logger.debug(`重置用户 ${userId} 的恢复尝试计数`);
  }
};

// 更新会话状态到数据库
const updateSessionStatus = async (userId, status) => {
  try {
    const db = require('../models');
    
    await db.WhatsappSession.update(
      { 
        status,
        endTime: status === 'disconnected' ? new Date() : null
      },
      {
        where: {
          userId,
          status: { [db.Sequelize.Op.ne]: 'disconnected' }
        }
      }
    );
    
    logger.debug(`更新用户 ${userId} 的会话状态为 ${status}`);
  } catch (error) {
    logger.error(`更新用户 ${userId} 会话状态失败:`, error);
  }
};

// 清理会话文件
const cleanupSessionFiles = async (userId) => {
  try {
    const sessionDir = path.resolve(config.whatsapp.dataPath, userId.toString());
    
    if (fs.existsSync(sessionDir)) {
      // 只清理临时文件，保留认证信息以便下次快速连接
      const tempFiles = [
        '.wwebjs_cache',
        'Default/Session Storage',
        'Default/Local Storage',
        'Default/IndexedDB'
      ];
      
      for (const tempFile of tempFiles) {
        const tempPath = path.join(sessionDir, tempFile);
        if (fs.existsSync(tempPath)) {
          fs.rmSync(tempPath, { recursive: true, force: true });
          logger.debug(`清理用户 ${userId} 的临时文件: ${tempFile}`);
        }
      }
    }
  } catch (error) {
    logger.error(`清理用户 ${userId} 会话文件时出错:`, error);
  }
};

// 连接失败重试逻辑
const connectionRetry = {
  // 重试配置
  maxRetries: 3,
  baseDelay: 5000, // 5秒
  maxDelay: 30000, // 30秒
  
  // 重试计数
  retryCount: new Map(),
  
  // 执行重试
  executeRetry: async (userId, initFunction) => {
    const currentRetries = connectionRetry.retryCount.get(userId) || 0;
    
    if (currentRetries >= connectionRetry.maxRetries) {
      logger.error(`用户 ${userId} 连接重试次数已达上限`);
      connectionRetry.retryCount.delete(userId);
      return false;
    }
    
    const delay = Math.min(
      connectionRetry.baseDelay * Math.pow(2, currentRetries),
      connectionRetry.maxDelay
    );
    
    logger.info(`用户 ${userId} 将在 ${delay}ms 后进行第 ${currentRetries + 1} 次重试`);
    
    return new Promise((resolve) => {
      setTimeout(async () => {
        try {
          connectionRetry.retryCount.set(userId, currentRetries + 1);
          
          const result = await initFunction();
          
          if (result) {
            logger.info(`用户 ${userId} 重试连接成功`);
            connectionRetry.retryCount.delete(userId);
            resolve(true);
          } else {
            logger.warn(`用户 ${userId} 重试连接失败`);
            
            // 继续下一次重试
            const nextResult = await connectionRetry.executeRetry(userId, initFunction);
            resolve(nextResult);
          }
        } catch (error) {
          logger.error(`用户 ${userId} 重试连接时出错:`, error);
          
          // 继续下一次重试
          const nextResult = await connectionRetry.executeRetry(userId, initFunction);
          resolve(nextResult);
        }
      }, delay);
    });
  },
  
  // 重置重试计数
  resetRetries: (userId) => {
    connectionRetry.retryCount.delete(userId);
  }
};

// 增强的初始化函数，包含重试逻辑
const initializeWhatsAppWithRetry = async (userId = 'default') => {
  try {
    // 首次尝试
    const result = await initializeWhatsApp(userId);
    
    if (result) {
      connectionRetry.resetRetries(userId);
      sessionManagement.resetRecoveryAttempts(userId);
      sessionManagement.cancelCleanup(userId);
      return true;
    }
    
    // 如果首次失败，启动重试机制
    logger.warn(`用户 ${userId} 初始化失败，启动重试机制`);
    
    return await connectionRetry.executeRetry(userId, () => initializeWhatsApp(userId));
  } catch (error) {
    logger.error(`用户 ${userId} 初始化过程出错:`, error);
    return false;
  }
};

// 增强的断开连接函数
const disconnectWhatsAppEnhanced = async (userId = 'default') => {
  try {
    logger.info(`开始断开用户 ${userId} 的WhatsApp连接`);
    
    // 取消清理和恢复定时器
    sessionManagement.cancelCleanup(userId);
    connectionRetry.resetRetries(userId);
    sessionManagement.resetRecoveryAttempts(userId);
    
    // 执行断开连接
    const result = await disconnectWhatsApp(userId);
    
    if (result.success) {
      // 更新会话状态
      await updateSessionStatus(userId, 'disconnected');
      
      // 安排会话清理
      sessionManagement.scheduleCleanup(userId);
    }
    
    return result;
  } catch (error) {
    logger.error(`断开用户 ${userId} 连接时出错:`, error);
    return { success: false, message: '断开连接失败: ' + error.message };
  }
};

// 会话健康检查
const sessionHealthCheck = {
  // 检查间隔（毫秒）
  checkInterval: 5 * 60 * 1000, // 5分钟
  
  // 健康检查定时器
  healthTimer: null,
  
  // 启动健康检查
  start: () => {
    if (sessionHealthCheck.healthTimer) {
      clearInterval(sessionHealthCheck.healthTimer);
    }
    
    sessionHealthCheck.healthTimer = setInterval(async () => {
      await sessionHealthCheck.performCheck();
    }, sessionHealthCheck.checkInterval);
    
    logger.info('会话健康检查已启动');
  },
  
  // 停止健康检查
  stop: () => {
    if (sessionHealthCheck.healthTimer) {
      clearInterval(sessionHealthCheck.healthTimer);
      sessionHealthCheck.healthTimer = null;
      logger.info('会话健康检查已停止');
    }
  },
  
  // 执行健康检查
  performCheck: async () => {
    try {
      logger.debug('开始执行会话健康检查');
      
      // 检查所有活跃的客户端
      for (const [userId, client] of whatsappClients.entries()) {
        try {
          const status = connectionStatuses.get(userId);
          
          if (status === 'connected') {
            // 检查客户端是否仍然有效
            const isValid = await checkClientHealth(userId, client);
            
            if (!isValid) {
              logger.warn(`用户 ${userId} 的客户端健康检查失败，尝试恢复`);
              
              // 标记为断开连接
              connectionStatuses.set(userId, 'disconnected');
              
              // 尝试恢复会话
              sessionManagement.attemptRecovery(userId);
            }
          }
        } catch (error) {
          logger.error(`检查用户 ${userId} 会话健康状态时出错:`, error);
        }
      }
    } catch (error) {
      logger.error('会话健康检查过程中出错:', error);
    }
  }
};

// 检查客户端健康状态
const checkClientHealth = async (userId, client) => {
  try {
    // 尝试获取客户端信息
    const info = await client.info;
    
    if (!info) {
      return false;
    }
    
    // 检查客户端状态
    const state = await client.getState();
    
    if (state !== 'CONNECTED') {
      return false;
    }
    
    return true;
  } catch (error) {
    logger.debug(`用户 ${userId} 客户端健康检查失败:`, error.message);
    return false;
  }
};

// 启动会话健康检查
sessionHealthCheck.start();

// 进程退出时清理
process.on('SIGTERM', () => {
  sessionHealthCheck.stop();
});

process.on('SIGINT', () => {
  sessionHealthCheck.stop();
});

/**
 * 初始化WhatsApp客户端
 * @param {string} userId 用户ID，用于多用户会话支持
 */
const initializeWhatsApp = async (userId = 'default') => {
  try {
    debugLogger.log('开始初始化WhatsApp客户端', { userId });
    
    // 检查是否已经存在该用户的客户端
    if (whatsappClients.has(userId) && connectionStatuses.get(userId) === 'connected') {
      logger.info(`用户 ${userId} 的WhatsApp客户端已初始化`);
      debugLogger.log('客户端已初始化', { userId, status: 'connected' });
      return true;
    }
    
    // 确保WhatsApp会话目录存在
    const sessionDir = path.resolve(config.whatsapp.dataPath, userId);
    if (!fs.existsSync(sessionDir)) {
      fs.mkdirSync(sessionDir, { recursive: true });
      debugLogger.log('创建会话目录', { path: sessionDir });
    }
    
    // 清理旧的会话文件，以避免可能的冲突
    try {
      const sessionPath = path.join(sessionDir, '.wwebjs_auth');
      if (fs.existsSync(sessionPath)) {
        logger.info(`清理WhatsApp会话: ${sessionPath}`);
        fs.rmSync(sessionPath, { recursive: true, force: true });
      }
    } catch (cleanError) {
      logger.error('清理会话出错:', cleanError);
      // 继续执行，不影响初始化流程
    }
    
    // 尝试使用Edge浏览器或Chrome
    let chromePath = process.env.CHROME_PATH;
    
    if (!chromePath) {
      // 尝试使用Edge浏览器（在Windows上更稳定）
      const edgePaths = [
        'C:\\Program Files\\Microsoft\\Edge\\Application\\msedge.exe',
        'C:\\Program Files (x86)\\Microsoft\\Edge\\Application\\msedge.exe'
      ];
      
      for (const path of edgePaths) {
        if (fs.existsSync(path)) {
          chromePath = path;
          logger.info(`使用Microsoft Edge浏览器: ${path}`);
          break;
        }
      }
    }
    
    if (!chromePath) {
      // 尝试Chrome
      const chromePaths = [
        'C:\\Program Files\\Google\\Chrome\\Application\\chrome.exe',
        'C:\\Program Files (x86)\\Google\\Chrome\\Application\\chrome.exe'
      ];
      
      for (const path of chromePaths) {
        if (fs.existsSync(path)) {
          chromePath = path;
          logger.info(`使用Google Chrome浏览器: ${path}`);
          break;
        }
      }
    }
    
    if (!chromePath) {
      chromePath = undefined;
      logger.info('未找到本地浏览器，使用Puppeteer内置的Chromium');
    }
    
    // 暂时不使用代理，因为测试表明不需要代理也能访问WhatsApp
    debugLogger.log('无需代理配置');
    logger.info('使用的puppeteer配置:', {
      headless: false,
      executablePath: chromePath || undefined,
      dataPath: sessionDir
    });
    
    // 使用最精简的必要参数
    const puppeteerArgs = [
      '--no-sandbox', 
      '--disable-setuid-sandbox',
      '--disable-dev-shm-usage',
      '--disable-gpu',
      '--disable-web-security',
      '--disable-features=IsolateOrigins,site-per-process',
      '--disable-blink-features=AutomationControlled'
    ];
    
    logger.info('使用简化的Chrome启动参数:', puppeteerArgs);
    
    // 创建客户端实例前先尝试简单的浏览器测试
    /* 暂时禁用浏览器测试，直接使用whatsapp-web.js
    try {
      logger.info('测试浏览器是否可以启动...');
      const puppeteer = require('puppeteer-core');
      const testBrowser = await puppeteer.launch({
        headless: true,
        executablePath: chromePath,
        args: ['--no-sandbox', '--disable-setuid-sandbox'],
        ignoreHTTPSErrors: true
      });
      await testBrowser.close();
      logger.info('浏览器测试成功');
    } catch (browserTestError) {
      logger.error('浏览器测试失败:', browserTestError);
      logger.error('错误详情:', browserTestError.message);
      
      // 如果是因为没有Chromium，尝试使用whatsapp-web.js内置的
      if (browserTestError.message.includes('chromium') || browserTestError.message.includes('executablePath')) {
        logger.info('尝试使用内置Chromium...');
        chromePath = undefined;
      } else {
        logger.error('浏览器启动失败，可能需要安装Visual C++ Redistributable或检查系统权限');
        return false;
      }
    }
    */
    
    // 创建客户端实例 - 使用更灵活的配置
    let whatsappClient;
    try {
      // 准备Puppeteer参数
      const puppeteerArgs = [
        '--no-sandbox',
        '--disable-setuid-sandbox',
        '--disable-dev-shm-usage',
        '--disable-gpu',
        '--disable-web-security',
        '--disable-features=IsolateOrigins,site-per-process',
        '--disable-blink-features=AutomationControlled',
        // 添加更多反检测参数
        '--disable-notifications',
        '--disable-default-apps',
        '--disable-extensions',
        '--disable-sync',
        '--disable-translate',
        '--no-first-run',
        '--disable-background-timer-throttling',
        '--disable-backgrounding-occluded-windows',
        '--disable-renderer-backgrounding',
        '--disable-features=TranslateUI',
        '--disable-ipc-flooding-protection',
        // 窗口大小
        '--window-size=1280,800',
        '--window-position=0,0',
        // 用户代理
        '--user-agent=Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/120.0.0.0 Safari/537.36'
      ];
      
      // 添加代理配置
      if (config.whatsapp.proxy && config.whatsapp.proxy.enabled) {
        const proxyConfig = config.whatsapp.proxy;
        
        if (proxyConfig.type === 'socks5') {
          // Socks5代理
          puppeteerArgs.push(`--proxy-server=socks5://${proxyConfig.host}:${proxyConfig.port}`);
          logger.info(`使用SOCKS5代理: ${proxyConfig.host}:${proxyConfig.port}`);
        } else if (proxyConfig.type === 'http') {
          // HTTP代理
          puppeteerArgs.push(`--proxy-server=http://${proxyConfig.host}:${proxyConfig.port}`);
          logger.info(`使用HTTP代理: ${proxyConfig.host}:${proxyConfig.port}`);
        }
      } else {
        logger.info('未配置代理，直接连接（可能无法访问WhatsApp）');
      }
      
      // 基础配置
      const clientConfig = {
        authStrategy: new LocalAuth({
          dataPath: sessionDir,
          clientId: userId
        }),
        puppeteer: {
          headless: false,
          args: puppeteerArgs,
          // 添加更多选项
          defaultViewport: null,
          ignoreHTTPSErrors: true
        }
      };
      
      // 只有在找到Chrome路径时才添加executablePath
      if (chromePath && fs.existsSync(chromePath)) {
        clientConfig.puppeteer.executablePath = chromePath;
        logger.info(`使用指定的浏览器: ${chromePath}`);
      } else {
        logger.info('使用whatsapp-web.js默认的Chromium');
        // 不指定executablePath，让whatsapp-web.js使用自己的Chromium
      }
      
      whatsappClient = new Client(clientConfig);
      
      // 设置初始连接状态
      connectionStatuses.set(userId, 'disconnected');
      
      // 注册事件处理程序
      registerWhatsAppEvents(whatsappClient, userId);
      
      // 初始化客户端
      logger.info(`正在初始化用户 ${userId} 的WhatsApp客户端...`);
      
      // 使用更安全的方式启动，增加重试逻辑
      let initSuccess = false;
      try {
        let retryCount = 0;
        const maxRetries = 3;
        
        while (retryCount < maxRetries && !initSuccess) {
          try {
            logger.info(`尝试初始化WhatsApp客户端 (尝试 ${retryCount + 1}/${maxRetries})...`);
            debugLogger.log(`初始化尝试 ${retryCount + 1}/${maxRetries}`);
            
            // 使用timeout.promise替代Promise.race
            const timeout = 120000; // 2分钟超时
            
            // 初始化客户端
            const initPromise = whatsappClient.initialize();
            
            // 设置超时
            const timeoutPromise = new Promise((_, reject) => {
              setTimeout(() => reject(new Error('初始化超时')), timeout);
            });
            
            // 等待初始化或超时
            await Promise.race([initPromise, timeoutPromise]);
            
            logger.info('WhatsApp客户端初始化成功!');
            debugLogger.log('初始化成功!');
            initSuccess = true;
          } catch (retryError) {
            retryCount++;
            logger.warn(`WhatsApp初始化尝试 ${retryCount}/${maxRetries} 失败: ${retryError.message}`);
            logger.error(`初始化错误详情:`, retryError);
            debugLogger.error(`初始化尝试失败 ${retryCount}/${maxRetries}`, retryError);
            
            if (retryError.message.includes('Protocol error') || 
                retryError.message.includes('Target closed') ||
                retryError.message.includes('net::ERR_PROXY_CONNECTION_FAILED')) {
              logger.error('协议错误或目标关闭，可能是网络连接问题');
            }
            
            // 清理会话并等待重试
            try {
              const sessionPath = path.join(sessionDir, '.wwebjs_auth');
              if (fs.existsSync(sessionPath)) {
                logger.info(`清理WhatsApp会话: ${sessionPath}`);
                fs.rmSync(sessionPath, { recursive: true, force: true });
              }
            } catch (cleanError) {
              logger.error('清理会话出错:', cleanError);
            }
            
            if (retryCount >= maxRetries) {
              logger.error(`达到最大重试次数(${maxRetries})，初始化失败`);
              throw retryError; // 达到最大重试次数，抛出最后一个错误
            }
            
            // 等待一段时间再重试
            const waitTime = 10000; // 等待10秒
            logger.info(`等待${waitTime/1000}秒后重试...`);
            await new Promise(resolve => setTimeout(resolve, waitTime));
          }
        }
      } catch (initError) {
        logger.error(`WhatsApp初始化过程错误:`, initError);
        logger.error(`错误类型: ${initError.constructor.name}`);
        logger.error(`错误信息: ${initError.message}`);
        logger.error(`错误堆栈: ${initError.stack}`);
        
        debugLogger.error('初始化过程致命错误', initError);
        
        if (initError.puppeteerError) {
          logger.error(`Puppeteer错误: ${initError.puppeteerError}`);
          debugLogger.error('Puppeteer错误', { puppeteerError: initError.puppeteerError });
        }
        
        throw initError;
      }
      
      // 保存客户端实例，仅在成功初始化后保存
      if (initSuccess) {
        whatsappClients.set(userId, whatsappClient);
        return true;
      } else {
        return false;
      }
    } catch (error) {
      logger.error(`用户 ${userId} 的WhatsApp客户端初始化失败:`, error);
      logger.error(`错误类型: ${error.constructor.name}`);
      logger.error(`错误信息: ${error.message}`);
      logger.error(`错误堆栈: ${error.stack}`);
      
      debugLogger.error('WhatsApp客户端初始化失败', error);
      
      // 检查是否存在嵌套错误
      if (error.cause) {
        logger.error(`原始错误: ${error.cause}`);
        debugLogger.error('原始错误', { cause: error.cause });
      }
      
      connectionStatuses.set(userId, 'disconnected');
      return false;
    }
  } catch (error) {
    logger.error(`用户 ${userId} 的WhatsApp客户端初始化失败:`, error);
    logger.error(`错误类型: ${error.constructor.name}`);
    logger.error(`错误信息: ${error.message}`);
    logger.error(`错误堆栈: ${error.stack}`);
    
    debugLogger.error('WhatsApp客户端初始化失败', error);
    
    // 检查是否存在嵌套错误
    if (error.cause) {
      logger.error(`原始错误: ${error.cause}`);
      debugLogger.error('原始错误', { cause: error.cause });
    }
    
    connectionStatuses.set(userId, 'disconnected');
    return false;
  }
};

/**
 * 注册WhatsApp事件处理
 * @param {Client} whatsappClient WhatsApp客户端实例
 * @param {string} userId 用户ID
 */
const registerWhatsAppEvents = (whatsappClient, userId) => {
  // 二维码生成事件
  whatsappClient.on('qr', (qr) => {
    logger.info(`用户 ${userId} 收到WhatsApp二维码`);
    qrCodes.set(userId, qr);
    connectionStatuses.set(userId, 'connecting');
    
    // 触发QR码更新回调
    if (callbacks.qrCodeUpdate.has(userId)) {
      callbacks.qrCodeUpdate.get(userId).forEach(cb => cb(null, qr));
    }
    
    // 向指定用户广播二维码更新
    global.io?.to(userId).emit('whatsapp:qr', { qr });
  });
  
  // 认证状态事件
  whatsappClient.on('authenticated', () => {
    logger.info(`用户 ${userId} WhatsApp认证成功`);
    qrCodes.delete(userId); // 清除二维码
  });
  
  // 认证失败事件
  whatsappClient.on('auth_failure', (msg) => {
    logger.error(`用户 ${userId} WhatsApp认证失败:`, msg);
    connectionStatuses.set(userId, 'disconnected');
    
    // 触发认证失败回调
    if (callbacks.authFailure.has(userId)) {
      callbacks.authFailure.get(userId).forEach(cb => cb(null, msg));
    }
    
    global.io?.to(userId).emit('whatsapp:status', { status: 'disconnected', message: '认证失败' });
  });
  
  // 准备就绪事件
  whatsappClient.on('ready', () => {
    logger.info(`用户 ${userId} WhatsApp客户端已准备就绪`);
    connectionStatuses.set(userId, 'connected');
    qrCodes.delete(userId); // 清除二维码
    
    // 触发客户端就绪回调
    if (callbacks.clientReady.has(userId)) {
      callbacks.clientReady.get(userId).forEach(cb => cb(null));
    }
    
    global.io?.to(userId).emit('whatsapp:status', { status: 'connected', message: '已连接' });
  });
  
  // 断开连接事件
  whatsappClient.on('disconnected', (reason) => {
    logger.info(`用户 ${userId} WhatsApp客户端已断开连接:`, reason);
    connectionStatuses.set(userId, 'disconnected');
    
    // 触发断开连接回调
    if (callbacks.disconnected.has(userId)) {
      callbacks.disconnected.get(userId).forEach(cb => cb(null, reason));
    }
    
    global.io?.to(userId).emit('whatsapp:status', { status: 'disconnected', message: '已断开连接' });
    
    // 清理客户端资源和定时器
    cleanupUserResources(userId);
  });
  
  // 消息接收事件
  whatsappClient.on('message', async (message) => {
    try {
      // 处理收到的消息
      const processedMessage = await messageService.processIncomingMessage(message);
      
      // 触发消息回调
      if (callbacks.message.has(userId)) {
        callbacks.message.get(userId).forEach(cb => cb(null, processedMessage));
      }
      
      // 通过WebSocket广播消息给指定用户
      global.io?.to(userId).emit('message:received', processedMessage);
    } catch (error) {
      logger.error(`用户 ${userId} 处理收到的消息时出错:`, error);
    }
  });
  
  // 消息状态变化事件
  whatsappClient.on('message_ack', (message, ack) => {
    try {
      // 状态码映射: 0=PENDING, 1=RECEIVED, 2=RECEIVED, 3=READ, 4=PLAYED
      const statusMap = {
        0: 'PENDING',
        1: 'SERVER_ACK',
        2: 'DELIVERY_ACK',
        3: 'READ',
        4: 'PLAYED'
      };
      
      const status = statusMap[ack] || 'UNKNOWN';
      
      // 触发消息状态变化回调
      if (callbacks.messageStatus.has(userId)) {
        callbacks.messageStatus.get(userId).forEach(cb => cb(message.from, message.id.id, status));
      }
      
      // 通知前端
      global.io?.to(userId).emit('message:status_change', {
        id: message.id.id,
        status: status
      });
    } catch (error) {
      logger.error(`用户 ${userId} 处理消息状态变化时出错:`, error);
    }
  });
  
  // 连接状态变化事件
  whatsappClient.on('change_state', (state) => {
    logger.info(`用户 ${userId} WhatsApp连接状态变化:`, state);
    
    // 触发连接状态变化回调
    if (callbacks.connectionState.has(userId)) {
      callbacks.connectionState.get(userId).forEach(cb => cb(null, state));
    }
    
    // 通知前端
    global.io?.to(userId).emit('whatsapp:connection_state', { state });
  });
  
  // 错误处理
  whatsappClient.on('error', (error) => {
    logger.error(`用户 ${userId} WhatsApp客户端错误:`, error);
    
    // 根据错误类型处理
    if (error.message && error.message.includes('browser')) {
      // 浏览器相关错误，可能需要重新初始化
      logger.warn(`用户 ${userId} 浏览器错误，尝试重新初始化...`);
      setTimeout(() => initializeWhatsApp(userId), 5000);
    }
  });
  
  // 联系人状态变化事件 - 可以通过轮询来模拟
  const contactStatusTimer = setInterval(async () => {
    if (whatsappClients.has(userId) && connectionStatuses.get(userId) === 'connected') {
      try {
        const subscriptions = contactSubscriptions.get(userId);
        if (subscriptions && subscriptions.size > 0) {
          const client = whatsappClients.get(userId);
          for (const contactId of subscriptions) {
            try {
              const contact = await client.getContactById(contactId);
              if (contact) {
                // 获取联系人状态
                const status = await contact.getStatus();
                const lastSeen = await contact.getLastSeen();
                
                // 更新联系人状态
                contact.status = status;
                contact.lastSeen = lastSeen;
                
                // 通知订阅此联系人的用户
                global.io?.to(userId).emit('contact:status_update', {
                  id: contactId,
                  status: status,
                  lastSeen: lastSeen
                });
              }
            } catch (err) {
              // 单个联系人出错不影响其他联系人
              logger.error(`用户 ${userId} 获取联系人 ${contactId} 状态失败:`, err);
            }
          }
        }
      } catch (error) {
        logger.error(`用户 ${userId} 轮询联系人状态时出错:`, error);
      }
    }
  }, 60000); // 每分钟更新一次
  
  // 保存定时器ID
  userTimers.set(userId, contactStatusTimer);
};

/**
 * 清理用户资源
 * @param {string} userId 用户ID
 */
const cleanupUserResources = (userId) => {
  // 清理定时器
  if (userTimers.has(userId)) {
    clearInterval(userTimers.get(userId));
    userTimers.delete(userId);
    logger.info(`已清理用户 ${userId} 的定时器`);
  }
  
  // 清理其他资源
  whatsappClients.delete(userId);
  qrCodes.delete(userId);
  connectionStatuses.delete(userId);
  contactSubscriptions.delete(userId);
  
  // 清理回调函数
  Object.keys(callbacks).forEach(key => {
    callbacks[key].delete(userId);
  });
};

/**
 * 获取当前连接状态
 * @param {string} userId 用户ID
 */
const getConnectionStatus = (userId = 'default') => {
  return {
    status: connectionStatuses.get(userId) || 'disconnected',
    qrCode: connectionStatuses.get(userId) === 'connecting' ? qrCodes.get(userId) : null
  };
};

/**
 * 获取当前二维码
 * @param {string} userId 用户ID
 */
const getQRCode = (userId = 'default') => {
  return qrCodes.get(userId);
};

/**
 * 断开WhatsApp连接
 * @param {string} userId 用户ID
 */
const disconnectWhatsApp = async (userId = 'default') => {
  if (whatsappClients.has(userId) && connectionStatuses.get(userId) === 'connected') {
    try {
      await whatsappClients.get(userId).destroy();
      connectionStatuses.set(userId, 'disconnected');
      cleanupUserResources(userId); // 使用统一的清理函数
      return { success: true, message: '已成功断开连接' };
    } catch (error) {
      logger.error(`用户 ${userId} 断开WhatsApp连接时出错:`, error);
      return { success: false, message: '断开连接时出错' };
    }
  }
  return { success: false, message: '当前未连接' };
};

/**
 * 发送消息
 * @param {string} to 接收者ID
 * @param {string} content 消息内容
 * @param {string} userId 发送者用户ID
 */
const sendMessage = async (to, content, userId = 'default') => {
  if (!whatsappClients.has(userId) || connectionStatuses.get(userId) !== 'connected') {
    throw new Error('WhatsApp客户端未连接');
  }
  
  try {
    const client = whatsappClients.get(userId);
    
    // 确保电话号码格式正确
    const formattedNumber = to.includes('@c.us') ? to : `${to}@c.us`;
    
    // 发送消息
    const response = await client.sendMessage(formattedNumber, content);
    
    // 记录发送的消息
    logger.info(`用户 ${userId} 发送消息成功`, { to: formattedNumber });
    
    return response;
  } catch (error) {
    logger.error(`用户 ${userId} 发送消息时出错:`, error);
    throw error;
  }
};

/**
 * 获取所有联系人
 */
const getAllContacts = async () => {
  if (!whatsappClients.size) {
    throw new Error('没有可用的WhatsApp客户端');
  }
  
  try {
    const contacts = await Promise.all(Array.from(whatsappClients.values()).map(client => client.getContacts()));
    return contacts.flat();
  } catch (error) {
    console.error('获取联系人时出错:', error);
    throw error;
  }
};

/**
 * 获取联系人信息
 * @param {string} contactId 联系人ID
 */
const getContactById = async (contactId) => {
  if (!whatsappClients.size) {
    throw new Error('没有可用的WhatsApp客户端');
  }
  
  try {
    const contact = await Promise.all(Array.from(whatsappClients.values()).map(client => client.getContactById(contactId)));
    return contact.find(c => c);
  } catch (error) {
    console.error('获取联系人时出错:', error);
    throw error;
  }
};

/**
 * 订阅联系人状态更新
 * @param {string} contactId 联系人ID
 * @param {string} userId 用户ID
 */
const subscribeContactStatus = async (contactId, userId) => {
  if (!contactId || !userId) {
    throw new Error('联系人ID和用户ID是必须的');
  }
  
  // 确保联系人ID格式正确
  const formattedId = contactId.includes('@c.us') ? contactId : `${contactId}@c.us`;
  
  // 如果该联系人没有订阅记录，创建一个新的
  if (!contactSubscriptions.has(formattedId)) {
    contactSubscriptions.set(formattedId, new Set());
  }
  
  // 添加用户到该联系人的订阅列表
  contactSubscriptions.get(formattedId).add(userId);
  
  return { success: true };
};

/**
 * 取消订阅联系人状态更新
 * @param {string} contactId 联系人ID
 * @param {string} userId 用户ID
 */
const unsubscribeContactStatus = async (contactId, userId) => {
  if (!contactId || !userId) {
    throw new Error('联系人ID和用户ID是必须的');
  }
  
  // 确保联系人ID格式正确
  const formattedId = contactId.includes('@c.us') ? contactId : `${contactId}@c.us`;
  
  // 如果该联系人有订阅记录，移除用户
  if (contactSubscriptions.has(formattedId)) {
    contactSubscriptions.get(formattedId).delete(userId);
    
    // 如果没有用户订阅该联系人，移除该联系人的订阅记录
    if (contactSubscriptions.get(formattedId).size === 0) {
      contactSubscriptions.delete(formattedId);
    }
  }
  
  return { success: true };
};

/**
 * 获取所有聊天
 */
const getAllChats = async () => {
  if (!whatsappClients.size) {
    logger.warn('WhatsApp服务不在线，返回空聊天列表');
    return []; // 返回空数组而不是抛出异常
  }
  
  try {
    const chats = await Promise.all(Array.from(whatsappClients.values()).map(client => client.getChats()));
    return chats.flat();
  } catch (error) {
    logger.error('获取聊天时出错:', error);
    return []; // 错误时也返回空数组
  }
};

/**
 * 标记聊天为已读
 * @param {string} chatId 聊天ID
 * @returns {boolean} 操作是否成功
 */
const markChatAsRead = async (chatId) => {
  if (!whatsappClients.size) {
    logger.warn('没有可用的WhatsApp客户端，无法标记聊天为已读');
    return false;
  }
  
  try {
    // 验证并格式化chatId
    if (!chatId) {
      logger.warn('标记聊天为已读：没有提供chatId');
      return false;
    }
    
    // 记录原始ID以便调试
    logger.info(`尝试标记聊天为已读，原始ID: ${chatId}`);
    
    // 处理各种可能的ID格式
    let formattedChatId = chatId;
    
    // 如果是数字或仅包含数字，添加@c.us后缀
    if (/^\d+$/.test(chatId)) {
      formattedChatId = `${chatId}@c.us`;
    } 
    // 如果已经包含@c.us，保持原样
    else if (chatId.includes('@c.us')) {
      formattedChatId = chatId;
    } 
    // 如果是复杂对象的JSON字符串，尝试解析
    else if (chatId.startsWith('{') && chatId.endsWith('}')) {
      try {
        const idObj = JSON.parse(chatId);
        if (idObj._serialized) {
          formattedChatId = idObj._serialized;
        } else if (idObj.id) {
          formattedChatId = idObj.id;
        }
      } catch (e) {
        logger.error(`解析复杂ID格式失败: ${e.message}`);
      }
    }
    // 处理旧格式ID：如果包含"-"，尝试替换为@c.us
    else if (chatId.includes('-')) {
      formattedChatId = chatId.replace(/-/g, '') + '@c.us';
    }
    
    logger.info(`格式化后的聊天ID: ${formattedChatId}`);
    
    const client = Array.from(whatsappClients.values())[0]; // 获取第一个可用客户端
    
    // 首先尝试直接查找聊天
    let chat = null;
    try {
      chat = await client.getChatById(formattedChatId).catch(() => null);
    } catch (err) {
      logger.warn(`通过ID直接获取聊天失败: ${err.message}，尝试其他方法`);
    }
    
    // 如果直接查找失败，获取所有聊天并遍历查找
    if (!chat) {
      logger.info('通过直接ID获取聊天失败，尝试在所有聊天中查找匹配项');
      const allChats = await client.getChats();
      
      for (const c of allChats) {
        // 检查各种可能的匹配方式
        const serializedId = c.id._serialized || '';
        const numericPart = serializedId.replace(/\D/g, '');
        
        if (
          serializedId === formattedChatId ||
          serializedId.includes(chatId) || 
          numericPart === chatId.replace(/\D/g, '') ||
          (c.name && c.name.includes(chatId))
        ) {
          logger.info(`在聊天列表中找到匹配: ${serializedId}`);
          chat = c;
          break;
        }
      }
    }
    
    if (!chat) {
      logger.error(`无法找到聊天: ${formattedChatId}`);
      return false;
    }
    
    // 标记为已读
    await chat.sendSeen();
    logger.info(`成功标记聊天 ${formattedChatId} 为已读`);
    return true;
  } catch (error) {
    logger.error(`标记聊天为已读时出错:`, error);
    return false;
  }
};

/**
 * 根据ID获取聊天
 */
const getChatById = async (chatId) => {
  if (!whatsappClients.size) {
    throw new Error('没有可用的WhatsApp客户端');
  }
  
  try {
    const chat = await Promise.all(Array.from(whatsappClients.values()).map(client => client.getChatById(chatId)));
    return chat.find(c => c);
  } catch (error) {
    console.error('获取聊天时出错:', error);
    throw error;
  }
};

/**
 * 获取特定聊天的消息历史
 * @param {string} chatId 聊天ID
 * @param {number} limit 消息数量限制
 * @param {string} beforeId 加载此消息ID之前的消息（用于分页）
 */
const getChatHistory = async (chatId, limit = 50, beforeId = null) => {
  if (!whatsappClients.size) {
    logger.warn('没有可用的WhatsApp客户端，返回空消息列表');
    return [];
  }
  
  try {
    // 验证并格式化参数
    if (!chatId) {
      logger.warn('获取聊天历史: 没有提供聊天ID');
      return [];
    }
    
    // 确保limit是有效的数字
    const validLimit = typeof limit === 'number' && limit > 0 ? 
      Math.min(limit, 100) : 50; // 最多返回100条
    
    // 格式化ID - 使用与markChatAsRead相同的逻辑
    let formattedChatId = chatId;
    
    // 如果是数字或仅包含数字，添加@c.us后缀
    if (/^\d+$/.test(chatId)) {
      formattedChatId = `${chatId}@c.us`;
    } 
    // 如果已经包含@c.us，保持原样
    else if (chatId.includes('@c.us')) {
      formattedChatId = chatId;
    } 
    // 如果是复杂对象的JSON字符串，尝试解析
    else if (typeof chatId === 'string' && chatId.startsWith('{') && chatId.endsWith('}')) {
      try {
        const idObj = JSON.parse(chatId);
        if (idObj._serialized) {
          formattedChatId = idObj._serialized;
        } else if (idObj.id) {
          formattedChatId = idObj.id;
        }
      } catch (e) {
        logger.error(`解析复杂ID格式失败: ${e.message}`);
      }
    }
    
    // 增加日志
    logger.info(`尝试获取聊天历史: ${formattedChatId}, 数量: ${validLimit}, 分页ID: ${beforeId || '无'}`);
    
    const client = Array.from(whatsappClients.values())[0]; // 获取第一个可用客户端
    
    // 验证聊天存在
    let chat;
    try {
      chat = await client.getChatById(formattedChatId);
      logger.info(`成功获取聊天对象: ${chat.id._serialized}, 名称: ${chat.name || '未命名'}`);
    } catch (chatErr) {
      logger.error(`获取聊天对象失败: ${chatErr.message}`);
      
      // 尝试加载该联系人的所有聊天对象
      const allChats = await client.getChats();
      logger.info(`当前系统中的聊天对象数量: ${allChats.length}`);
      
      // 记录所有聊天对象以便调试
      allChats.forEach(c => logger.info(`聊天对象: ${c.id._serialized}, 名称: ${c.name || '未命名'}`));
      
      // 尝试用不同方式寻找
      chat = allChats.find(c => {
        const serializedId = c.id._serialized || '';
        const numericPart = serializedId.replace(/\D/g, '');
        
        return serializedId === formattedChatId || 
                serializedId.includes(chatId) || 
                numericPart === chatId.replace(/\D/g, '') ||
                (c.name && c.name.includes(chatId));
      });
      
      if (!chat) {
        logger.error(`聊天对象不存在: ${chatId}`);
        return []; // 如果找不到聊天，返回空数组
      }
      
      logger.info(`使用替代方法找到聊天对象: ${chat.id._serialized}`);
    }
    
    // 使用分页参数获取聊天记录
    const options = { limit: validLimit };
    if (beforeId) {
      // 尝试查找特定消息对象作为分页标记
      try {
        logger.info(`尝试定位分页消息: ${beforeId}`);
        const beforeMsg = await chat.findMessageById(beforeId);
        if (beforeMsg) {
          options.before = beforeMsg;
          logger.info('成功找到分页消息对象');
        } else {
          logger.warn(`找不到分页消息: ${beforeId}`);
        }
      } catch (msgErr) {
        logger.warn(`查找分页消息出错: ${msgErr.message}`);
        // 如果找不到消息对象，退回到字符串ID
        options.before = beforeId;
      }
    }
    
    // 设置更长的超时时间
    const timeoutPromise = new Promise((_, reject) => 
      setTimeout(() => reject(new Error('获取聊天记录超时')), 60000));
    
    // 获取聊天记录并设置超时
    logger.info(`开始获取聊天记录，参数:`, options);
    
    let messages = [];
    try {
      const messagesPromise = chat.fetchMessages(options);
      messages = await Promise.race([messagesPromise, timeoutPromise]);
      logger.info(`成功获取原始消息: ${messages.length}条`);
    } catch (fetchErr) {
      logger.error(`获取消息失败: ${fetchErr.message}`);
      
      // 尝试使用替代方法 - 某些版本的API可能不同
      try {
        logger.info('尝试使用替代方法获取消息...');
        messages = await chat.getMessages({ limit: validLimit });
        
        // 如果需要分页，手动过滤
        if (beforeId && messages.length > 0) {
          const beforeIndex = messages.findIndex(m => m.id._serialized === beforeId || m.id.id === beforeId);
          if (beforeIndex > 0) {
            messages = messages.slice(0, beforeIndex);
          }
        }
      } catch (altErr) {
        logger.error(`替代获取消息方法也失败: ${altErr.message}`);
        return []; // 两种方法都失败时返回空数组
      }
    }
    
    // 如果没有获取到消息，可能是因为新创建的聊天，返回空数组
    if (!messages || messages.length === 0) {
      logger.info(`聊天 ${chatId} 没有历史记录或历史记录为空`);
      return [];
    }
    
    // 记录原始消息结构
    logger.info(`第一条原始消息结构:`, JSON.stringify(messages[0], (key, value) => {
      if (key === 'data' && typeof value === 'string' && value.length > 50) {
        return `${value.substring(0, 50)}...`;
      }
      return value;
    }));
    
    // 处理消息对象，确保客户端可以正确处理
    const processedMessages = messages.map((msg, index) => {
      try {
        // 检查消息是否有效
        if (!msg) {
          logger.warn(`跳过第${index+1}条消息: 消息对象为空`);
          return null;
        }
        
        // 提取消息ID
        let msgId = '';
        if (msg.id) {
          msgId = typeof msg.id === 'object' ? (msg.id._serialized || msg.id.id) : msg.id;
        } else {
          msgId = `temp_${Date.now()}_${index}`;
        }
        
        // 提取消息内容
        let msgBody = '';
        if (msg.body !== undefined) {
          msgBody = msg.body;
        } else if (msg._data && msg._data.body) {
          msgBody = msg._data.body;
        } else {
          msgBody = '内容不可用';
          logger.warn(`消息${msgId}内容为空`);
        }
        
        // 提取发送方信息
        const fromInfo = msg.from || (msg.fromMe ? 'me' : formattedChatId);
        
        // 构建标准消息格式
        const standardMsg = {
          id: msgId,
          body: msgBody,
          fromMe: msg.fromMe || false,
          from: {
            id: typeof fromInfo === 'object' ? (fromInfo.user || fromInfo.id || 'unknown') : fromInfo
          },
          to: msg.to || formattedChatId,
          timestamp: msg.timestamp || new Date().toISOString(),
          type: msg.type || 'text',
          // 添加调试信息
          _debug: {
            originalType: typeof msg,
            hasBody: msg.body !== undefined,
            hasId: msg.id !== undefined,
            index: index
          }
        };
        
        return standardMsg;
      } catch (procErr) {
        logger.warn(`处理第${index+1}条消息时出错: ${procErr.message}`);
        // 出错时返回基本消息
        return {
          id: `error_${Date.now()}_${index}`,
          body: '消息处理失败',
          fromMe: false,
          from: { id: 'system' },
          to: formattedChatId,
          timestamp: new Date().toISOString(),
          type: 'text',
          error: procErr.message
        };
      }
    }).filter(Boolean); // 过滤掉null
    
    logger.info(`成功转换 ${processedMessages.length}/${messages.length} 条消息到标准格式`);
    return processedMessages;
  } catch (error) {
    logger.error(`获取聊天历史时出错:`, error);
    logger.error(`错误详细信息: ${error.stack}`);
    // 返回空数组而不是抛出错误，这样前端仍然可以正常显示界面
    return [];
  }
};

/**
 * 发送文件
 */
const sendFile = async (to, filePath, caption = '', userId = 'default') => {
  if (!whatsappClients.has(userId) || connectionStatuses.get(userId) !== 'connected') {
    throw new Error('WhatsApp客户端未连接');
  }
  
  try {
    const client = whatsappClients.get(userId);
    
    // 确保电话号码格式正确
    const formattedNumber = to.includes('@c.us') ? to : `${to}@c.us`;
    
    // 获取媒体对象
    const media = MessageMedia.fromFilePath(filePath);
    
    // 发送文件
    const response = await client.sendMessage(formattedNumber, media, {
      caption
    });
    
    return response;
  } catch (error) {
    console.error('发送文件时出错:', error);
    throw error;
  }
};

/**
 * 发送图片
 */
const sendImage = async (to, media, caption = '', userId = 'default') => {
  if (!whatsappClients.has(userId) || connectionStatuses.get(userId) !== 'connected') {
    throw new Error('WhatsApp客户端未连接');
  }
  
  try {
    const client = whatsappClients.get(userId);
    
    // 确保电话号码格式正确
    const formattedNumber = to.includes('@c.us') ? to : `${to}@c.us`;
    
    // 发送图片
    const response = await client.sendMessage(formattedNumber, media, {
      caption
    });
    
    return response;
  } catch (error) {
    console.error('发送图片时出错:', error);
    throw error;
  }
};

// 回调注册函数
const onQRCodeUpdate = (callback, userId = 'default') => {
  if (!callbacks.qrCodeUpdate.has(userId)) {
    callbacks.qrCodeUpdate.set(userId, []);
  }
  callbacks.qrCodeUpdate.get(userId).push(callback);
};

const onClientReady = (callback, userId = 'default') => {
  if (!callbacks.clientReady.has(userId)) {
    callbacks.clientReady.set(userId, []);
  }
  callbacks.clientReady.get(userId).push(callback);
};

const onAuthFailure = (callback, userId = 'default') => {
  if (!callbacks.authFailure.has(userId)) {
    callbacks.authFailure.set(userId, []);
  }
  callbacks.authFailure.get(userId).push(callback);
};

const onDisconnected = (callback, userId = 'default') => {
  if (!callbacks.disconnected.has(userId)) {
    callbacks.disconnected.set(userId, []);
  }
  callbacks.disconnected.get(userId).push(callback);
};

const onMessage = (callback, userId = 'default') => {
  if (!callbacks.message.has(userId)) {
    callbacks.message.set(userId, []);
  }
  callbacks.message.get(userId).push(callback);
};

const onMessageStatusChange = (callback, userId = 'default') => {
  if (!callbacks.messageStatus.has(userId)) {
    callbacks.messageStatus.set(userId, []);
  }
  callbacks.messageStatus.get(userId).push(callback);
};

const onContactStatusChange = (callback, userId = 'default') => {
  if (!callbacks.contactStatus.has(userId)) {
    callbacks.contactStatus.set(userId, []);
  }
  callbacks.contactStatus.get(userId).push(callback);
};

const onBatteryStatus = (callback, userId = 'default') => {
  if (!callbacks.batteryStatus.has(userId)) {
    callbacks.batteryStatus.set(userId, []);
  }
  callbacks.batteryStatus.get(userId).push(callback);
};

const onConnectionStateChange = (callback, userId = 'default') => {
  if (!callbacks.connectionState.has(userId)) {
    callbacks.connectionState.set(userId, []);
  }
  callbacks.connectionState.get(userId).push(callback);
};

/**
 * 获取活跃客户端数量
 */
const getActiveClientsCount = () => {
  return whatsappClients.size;
};

/**
 * 获取所有连接状态
 */
const getAllConnectionStatuses = () => {
  const statuses = {};
  for (const [userId, status] of connectionStatuses.entries()) {
    statuses[userId] = status;
  }
  return statuses;
};

module.exports = {
  initializeWhatsApp,
  getConnectionStatus,
  getQRCode,
  disconnectWhatsApp,
  sendMessage,
  getAllContacts,
  getContactById,
  subscribeContactStatus,
  unsubscribeContactStatus,
  getAllChats,
  getChatById,
  getChatHistory,
  markChatAsRead,
  sendFile,
  sendImage,
  // 回调注册函数
  onQRCodeUpdate,
  onClientReady,
  onAuthFailure,
  onDisconnected,
  onMessage,
  onMessageStatusChange,
  onContactStatusChange,
  onBatteryStatus,
  onConnectionStateChange,
  initializeWhatsAppWithRetry,
  disconnectWhatsAppEnhanced,
  sessionManagement,
  connectionRetry,
  sessionHealthCheck,
  getActiveClientsCount,
  getAllConnectionStatuses
}; 